//
//  NewsTableViewController.m
//  LWB_Project
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 wangjianliang. All rights reserved.
//
#import "NewsTableViewController.h"
#import "WNetDealTools.h"
#import "NewsModels.h"
#import "FirstNewsTableViewCell.h"
#import "SecondNewsTableViewCell.h"
#import "CarouselMap.h"
#import "NewsDetailTableViewController.h"
#import "MBProgressHUD.h"
#import "DebugNSLog.h"
#import "DataBasehandle.h"
#import "YyxHeaderRefresh.h"
#import "MJRefresh.h"
@interface NewsTableViewController ()
{
    BOOL isReshing;
    BOOL isLoading;
}
@property (nonatomic, strong) UIView *headerView;//头部视图
@property (nonatomic, strong) CarouselMap *CarouselMapView;//轮播视图
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIView *buttonView;//按钮的背景
@property (nonatomic,retain) MBProgressHUD * hud;//菊花图标

@property (nonatomic, assign) BOOL NETStates;   //网络状态

@property (nonatomic, assign) NewsType NewsTypes; //新闻的当前类型

@property (strong, nonatomic) YyxHeaderRefresh *refresh; //下拉刷新


@property (nonatomic, assign) NSInteger currentPage;//当前的业数

@property (nonatomic, assign) BOOL loadDateBit; //上拉加载标志 这时候不清除数据库 元素

@end

@implementation NewsTableViewController
static NSInteger lastbuttontag;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //创建 轮播图加载到 tableView的HeaderView上
    [self loadCarouselMapView];
    
    #pragma mark--- 自定义视图切换的View
    [self customNavgationbarTitleView];
    
    //加载图标
    [self p_setupProgressHud];
    
    //初始化状态
    self.NewsTypes =NewsTypeHeadlines;
    _currentPage = 0;
    
    #pragma mark--- 判断网络类型！
    #pragma mark--- 根据网络连接来判断 是否下载数据上拉刷新 下来加载
    [WNetDealTools checkNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                MyLog(@"网络状态：未知");
                self.NETStates = NO;
                //没有数据库 加载数据库
                [self loadSQLNewsmodel:self.NewsTypes];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                 MyLog(@"网络状态：无连接");
                self.NETStates = NO;
                //没有数据库 加载数据库
                [self loadSQLNewsmodel:self.NewsTypes];
                
                
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                 MyLog(@"网络状态：3G");
                self.NETStates = YES;
                 #pragma mark--- 加载默认的新闻类型
                [self switchNewType:self.NETStates Pages:_currentPage];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                 MyLog(@"网络状态：局域网络Wifi");
                self.NETStates = YES;
                #pragma mark--- 加载默认的新闻类型
                [self switchNewType:self.NewsTypes Pages:_currentPage];
                break;
            default:
                break;
        }
        
    }];
    
    

    //猫的下拉刷新图标
    self.refresh = [YyxHeaderRefresh header];
    self.refresh.tableView = self.tableView;
    __weak NewsTableViewController *vc = self;
    self.refresh.beginRefreshingBlock = ^(YyxHeaderRefresh *refreshView)
    {
        //清空
        vc.dataArray = [[NSMutableArray alloc] init];
        [vc.tableView reloadData];
        vc.currentPage = 0;
       //下载
       [vc switchNewType:vc.NewsTypes Pages: vc.currentPage];
    };
    
    __block NewsTableViewController *newVC = self;
    //上拉加载:
    [self.tableView addFooterWithCallback:^{
        if (newVC->isReshing) {
            return;
        }
        newVC.loadDateBit = YES;
        newVC->isLoading = YES;
        [vc switchNewType:vc.NewsTypes Pages: vc.currentPage];
        newVC->isLoading = NO;
        newVC.loadDateBit = NO;
        [newVC.tableView footerEndRefreshing];
    }];

    
}


#pragma mark--- 初始化菊花图标
-(void)p_setupProgressHud{
    
    self.hud = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width , self.view.frame.size.height)];
    self.hud.frame = self.view.bounds;
    self.hud.minSize = CGSizeMake(100, 100);
    self.hud.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:self.hud];
    self.hud.dimBackground = YES;
    self.hud.labelText = @"loading";
    self.hud.backgroundColor = [UIColor clearColor];
    [self.hud show:NO];
    
}
-(void)loadSQLNewsmodel:(NewsType )type
{
    //没有数据库 加载数据库
    DataBasehandle *db = [DataBasehandle sharedDataBasehandle];
    //进行判断type的类型
    [db createtableName:[self getNewsSqliteName:type] Modelclass:[NewsModels class]];
    //读出来数据库里边的东西
    self.dataArray = [db selectAllModel];
    
    //界面的操作
    //把轮播图去掉！
    {
     for( UIView *view in [self.CarouselMapView subviews] )
     {
         [view removeFromSuperview];
     }
    }
    //隐藏菊花图标
    [self.hud hide:YES];
    //如果没有数据库 界面不添加任何的图标 有的话添加轮播图
    if (self.dataArray.count != 0)
    {

        //刷新轮播图
        [self LunBoRefresh];
        
        //刷新tableview
        [self.tableView reloadData];
        
    }
    
    //提示
    [self  checkNetalerView];


}


#pragma mark--- 切换不同的新闻类型！！！
-(void)switchNewType:(NewsType )type Pages:(NSInteger ) page
{
    static NSInteger currentType = -1;
    static NSInteger oldType = -1;
    
    #pragma mark--- 当新闻类型改变的时候 从新初始化数组
    currentType = type;
    if (currentType != oldType)
    {
       self.dataArray = [[NSMutableArray alloc] init];
       [self.tableView reloadData];
        _currentPage = 0;
    }
    oldType = currentType;
    
    //记录那个新闻的状态
    self.NewsTypes = type;
    
    //如果有网络
    if (self.NETStates == YES)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             //菊花转
             self.hud.labelText = @"正在加载数据";
             [self.hud show:YES];
         });


    #pragma mark--- 解耦一下
            __weak NewsTableViewController *vc = self;
            [WNetDealTools GetNewsModelNewType:type Pages:page block:^(NSArray *ModelArray)
             {
    #pragma mark--- 添加上下载下来的数组 到本地的 vc.dataArray
                 //排除解析不了的model!!!!!!!!
                 for (NewsModels *model in ModelArray)
                 {
                      if ([model.TAGS isEqualToString:@"画报"] || [model.TAGS isEqualToString:@"正在直播"]) {
                          continue;
                      }
                      if ([model.editorBit isEqualToString:@"YES"]) {
                          continue;
                      }
                     
                     [vc.dataArray addObject:model];
                 }
                 
                 [vc.tableView reloadData];
                 
    #pragma mark--- 把轮播图的图片加上！
                 [vc LunBoRefresh];
                 
                 //菊花停止！
                 //加载图标隐藏
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     [vc.hud hide:YES];
                 });
                 [vc.refresh endRefreshing];
                 
                 //有网的时候保存数据库
                 #pragma mark---  这里边用一个函数返回 表名  根据现在的状态
                 DataBasehandle *db = [DataBasehandle sharedDataBasehandle];
                 [db createtableName:[vc getNewsSqliteName:type] Modelclass:[NewsModels class]];
                 if (vc.loadDateBit == NO)//只要不是上拉加载状态就清空数据库
                 [db DeleteTbaleName:[vc getNewsSqliteName:type]]; //清空数据库所有的元素
                 //所有元素插入数据库
                 for (int i = 0; i < vc.dataArray.count; i++)
                 {
                     [db insertIntoTableModel:vc.dataArray[i]];
                 }
                 
                 //当前的业可以继续 往后网络下载数据！
                 if (ModelArray.count >= 20) vc.currentPage++;
                 
             }];

    }
    else
    {
        //读出来model 判断一下  再把数据刷新 轮播图加上！
        [self  loadSQLNewsmodel:type];
    
    }
}

#pragma mark----创建头部视图
 - (void)loadHeaderView
{
    self.navigationController.navigationBar.translucent = NO;
    self.tableView.tableHeaderView = self.CarouselMapView;
}

#pragma mark--- 创建轮播视图
-(void)loadCarouselMapView
{
    #pragma mark--- 这里要屏幕适配
    self.CarouselMapView = [[CarouselMap alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/3 )];
    
    __weak NewsTableViewController * blockvc = self;
    self.CarouselMapView.block = ^(NSInteger index)
    {
        if (blockvc.NETStates == YES)
        {
            NewsDetailTableViewController *vc = [[NewsDetailTableViewController alloc] init];
            vc.model = blockvc.dataArray[index];
            [blockvc.navigationController pushViewController:vc animated:NO];
        }else
        {
          [blockvc checkNetalerView];
        }
    };
    
    #pragma mark--- 创建头部的headerView
    [self loadHeaderView];

}

#pragma mark--- 刷新轮播图
-(void)LunBoRefresh
{
    self.CarouselMapView.imageUrlStringArray = [[NSMutableArray alloc] init];
    self.CarouselMapView.titleArray  = [[NSMutableArray alloc] init];
    for (int i = 0; i < 3; i++)
    {
        NewsModels *model = self.dataArray[i];
        [self.CarouselMapView.imageUrlStringArray addObject:model.imgsrc];
        [self.CarouselMapView.titleArray addObject:model.title];
    }
    [self.CarouselMapView changeImage];
}

#pragma mark--- 自定义titlebarTitleView
-(void)customNavgationbarTitleView
{
    //创建scrollVeiw
    UIScrollView *scrollview;
    scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, 44)];
    scrollview.backgroundColor = [UIColor whiteColor];
    scrollview.showsHorizontalScrollIndicator = YES;
    scrollview.showsVerticalScrollIndicator = NO;
    //scrollview.pagingEnabled = YES;
    scrollview.contentSize = CGSizeMake(self.view.frame.size.width*2, 44);
    self.navigationItem.titleView = scrollview ;
    
    //先添加一个那啥 背景
    CGFloat w = self.view.frame.size.width*2/9;
    self.buttonView = [[UIView alloc] init];
    self.buttonView.backgroundColor = [UIColor greenColor];
    self.buttonView.frame = CGRectMake(0, 0, 50, 40);
    self.buttonView.layer.masksToBounds = YES;
    self.buttonView.layer.cornerRadius = 20;
    [scrollview addSubview:self.buttonView];
    
    //创建9个button添加到scrollView上
    for (int i = 0; i < 9; i++) {
       
        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        button.frame= CGRectMake(w * i, 0, 50, 40);
        button.tag = 100 + i;
        [button addTarget:self action:@selector(ButtonCilck:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:[self getURLWithIndex:i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        button.backgroundColor=[UIColor clearColor];
        [scrollview addSubview:button];
    }
    lastbuttontag = 0;
    

}
#pragma mark--- 点击方法  static NSInteger lastbuttontag;
-(void)ButtonCilck:(UIButton *)btn
{
    
    UIScrollView *scrollView = (UIScrollView *)self.navigationItem.titleView;
     __block NSInteger x;
     __block   CGFloat w = self.view.frame.size.width*2/9;
    [UIView animateWithDuration:0.5 animations:^{
    
        if ((btn.tag-100) - lastbuttontag >= 0 )
        {
            x = (btn.tag-100) - lastbuttontag;
            CGFloat currentX = scrollView.contentOffset.x;
            [scrollView setContentOffset:CGPointMake(currentX + 1*w , 0)];
        }else
        {
            x =  lastbuttontag - (btn.tag-100);
            CGFloat currentX = scrollView.contentOffset.x;
            [scrollView setContentOffset:CGPointMake(currentX - 1*w , 0)];
        }
        
        CGFloat currentX = scrollView.contentOffset.x;
        if (currentX <= 0) {
            [scrollView setContentOffset:CGPointMake(0 , 0)];
        }
        if (currentX >= [UIScreen mainScreen].bounds.size.width) {
            [scrollView setContentOffset:CGPointMake([UIScreen mainScreen].bounds.size.width , 0)];
        }
        
        _buttonView.frame = btn.frame;
        

    }];
    
    #pragma mark--- 没网的时候界面 会出先动画！
    [self switchNewType:(NewsType)(btn.tag-100) Pages:0];
    
    lastbuttontag = btn.tag - 100;
    
}

#pragma mark--- 获取相应地新闻类型的文字
- (NSString *)getURLWithIndex:(NewsType)type
{
    NSString *str;
    
    switch (type)
    {
        case NewsTypeHeadlines: str = @"头条";
            break;
        case NewsTypeRecreation: str = @"娱乐";
            break;
        case NewsTypeSports: str = @"体育";
            break;
        case NewsTypeFinancial: str = @"财经";
            break;
        case NewsTypeTechnology: str = @"科技";
            break;
        case NewsTypeCar: str = @"汽车";
            break;
        case NewsTypeFashion: str = @"时尚";
            break;
        case NewsTypeMilitary: str = @"军事";
            break;
        case NewsTypeGame: str = @"游戏";;
            break;
            
        default:
            break;
    }
    return str;
}
#pragma mark--- 获取新闻类型所对应数据库的名字
- (NSString *)getNewsSqliteName:(NewsType)type
{
    NSString *str;
    
    switch (type)
    {
        case NewsTypeHeadlines: str = @"NewsTypeHeadlines";
            break;
        case NewsTypeRecreation: str = @"NewsTypeRecreation";
            break;
        case NewsTypeSports: str = @"NewsTypeSports";
            break;
        case NewsTypeFinancial: str = @"NewsTypeFinancial";
            break;
        case NewsTypeTechnology: str = @"NewsTypeTechnology";
            break;
        case NewsTypeCar: str = @"NewsTypeCar";
            break;
        case NewsTypeFashion: str = @"NewsTypeFashion";
            break;
        case NewsTypeMilitary: str = @"NewsTypeMilitary";
            break;
        case NewsTypeGame: str = @"NewsTypeGame";;
            break;
            
        default:
            break;
    }
    return str;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count-3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
#pragma mark--- 自定义cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    
    #pragma mark--- 提取model 轮播图占用了 前3个 model
    NewsModels *model = self.dataArray[indexPath.row + 3];
    
    if ([model.skipType isEqualToString:@"photoset"])
    {
        //修正bug补丁
        
        if((model.imgextra1 == nil)  && (model.imgextra2 == nil))
        {
           FirstNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstNewsTableViewCell" ];
            if (cell == nil)
            {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"FirstNewsTableViewCell" owner:self options:nil] firstObject];
            }
            [cell setModel:model];
            
            return cell;
        }else
        {
        
          SecondNewsTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondNewsTableViewCell" ];
            if (cell == nil)
            {
              cell = [[[NSBundle mainBundle] loadNibNamed:@"SecondNewsTableViewCell" owner:self options:nil] firstObject];
            }
            
            [cell setModel:model];
            return cell;
        }


    }else
    {
        FirstNewsTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstNewsTableViewCell" ];
        if (cell == nil)
        {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"FirstNewsTableViewCell" owner:self options:nil] firstObject];
        }
        [cell setModel:model];
        return cell;
    }
}


#pragma mark--- 跳到下个界面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //如果有网络
    if (self.NETStates == YES)
    {
        NewsDetailTableViewController *vc = [[NewsDetailTableViewController alloc] init];
        vc.model = self.dataArray[indexPath.row+3];
        [self.navigationController pushViewController:vc animated:YES];
    }else
    {
    
        [self checkNetalerView];
    }
}

-(void)checkNetalerView
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络连接" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
    [alertView show];
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Table view delegate
 
 // In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 // Navigation logic may go here, for example:
 // Create the next view controller.
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
 
 // Pass the selected object to the new view controller.
 
 // Push the view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
